import Vue from 'vue'
import axios from 'axios'
import {store} from '../vuex/store'

//请求计数
let isLoading = 0;
function isShow() {
  // 每次请求 isLoading+1,请求完成-1并调用次方法
  // 值不为0时，一直显示等待动画
  if(isLoading == 0){
    // setTimeout(()=>{
      store.commit('updateLoadingStatus', {isLoading: false})
    // },4000)
  }
}


//格式化参数
function parame (arr){
  let url = ''
  for (var a in arr){
    url += a + '=' + arr[a] + '&'
  }
  if(url != ''){
    return url.substring(0,url.length - 1)
  }
  return url
}

let req = 'http://em.bosye.com:8081'
// let req = ''

axios.defaults.timeout = 30000;

Vue.mixin({
  created(){
    this.apiGet = (url,data)=>{
      store.commit('updateLoadingStatus', {isLoading: true})
      isLoading++
      if(typeof data == 'object') data = parame(data)
      return new Promise ((resolve,reject)=>{
        axios.get(req+url,data).then((res)=>{
          resolve(res.data)
          isLoading--
          isShow()
        },(err)=>{
          reject(err)
          isLoading = 0
          isShow()
        })
      })
    }
    this.apiPost = (url,data)=>{
      store.commit('updateLoadingStatus', {isLoading: true})
      isLoading++
      if(typeof data == 'object') data = parame(data)
      return new Promise ((resolve,reject)=>{
        axios.post(req+url,data).then((res)=>{
          resolve(res.data)
          isLoading--
          isShow()
        },(err)=>{
          reject(err)
          isLoading = 0
          isShow()
        })
      })
    }
  }
})